<template>
  <div class="container">
    <Breadcrumb :items="['${functionName!}模块', '${functionName!}管理']" />
    <a-card class="general-card" :title="$t('menu.list.searchTable')">
      <a-row>
        <a-col :flex="1">
          <a-form
            :model="formModel"
            :label-col-props="{ span: 6 }"
            :wrapper-col-props="{ span: 18 }"
            label-align="left"
          >

            <a-row :gutter="16">
              <#list columnRows as columnRow>
                <#if columnRow.queryWhether?? && columnRow.queryWhether=="Y">
                  <a-col :span="8">
                      <a-form-item field="${columnRow.fieldName}" label="${columnRow.fieldRemark}">
                    <#if columnRow.effectType=="INPUT">
                      <a-input v-model="formModel.${columnRow.fieldName}" placeholder="请输入${columnRow.fieldRemark}"/>
                    <#elseif columnRow.effectType=="INPUT_NUMBER">
                      <a-input-number  v-model="formModel.${columnRow.fieldName}" placeholder="请输入${columnRow.fieldRemark}">
                    <#elseif columnRow.effectType=="INPUT_TAG">
                      <a-input-tag  placeholder="请输入${columnRow.fieldRemark}"  v-model="formModel.${columnRow.fieldName}" allow-clear/>
                    <#elseif columnRow.effectType=="SELECT">
                      <a-select :style="{width:'320px'}" v-model="formModel.${columnRow.fieldName}" placeholder="请输入${columnRow.fieldRemark} ...">
                        <a-option>Beijing</a-option>
                        <a-option>Shanghai</a-option>
                        <a-option>Guangzhou</a-option>
                        <a-option disabled>Disabled</a-option>
                      </a-select>
                     <#elseif columnRow.effectType=="DATEPICKER_YMD">
                      <a-date-picker style="width: 200px;" v-model="formModel.${columnRow.fieldName}" allow-clear/>
                     <#elseif columnRow.effectType=="DATEPICKER_YMD_HMS">
                      <a-date-picker style="width: 200px;" v-model="formModel.${columnRow.fieldName}"   format="YYYY-MM-DD HH:mm:ss" allow-clear/>
                     <#elseif columnRow.effectType=="DATEPICKER_YMD_RANGE">
                      <a-range-picker style="width: 200px;" v-model="formModel.${columnRow.fieldName}" show-time format="YYYY-MM-DD"  allow-clear/>
                     <#else>
                      <a-input v-model="formModel.${columnRow.fieldName}" placeholder="请输入${columnRow.fieldRemark}"/>
                  </#if>
                      </a-form-item>
                  </a-col>
                </#if>
              </#list>
            </a-row>
          </a-form>
        </a-col>
        <a-divider style="height: 84px" direction="vertical" />
        <a-col :flex="'86px'" style="text-align: right">
          <a-space direction="vertical" :size="18">
            <a-button type="primary" @click="search">
              <template #icon>
                <icon-search />
              </template>
              查询
            </a-button>
            <a-button @click="reset">
              <template #icon>
                <icon-refresh />
              </template>
             重置
            </a-button>
          </a-space>
        </a-col>
      </a-row>

      <a-divider style="margin-top: 0" />
      <a-row style="margin-bottom: 16px">
        <a-col :span="12">
          <a-space>
            <a-button type="primary" @click="add">
              <template #icon>
                <icon-plus />
              </template>
             创建
            </a-button>
          </a-space>
        </a-col>
        <a-col
          :span="12"
          style="display: flex; align-items: center; justify-content: end"
        >
          <a-tooltip :content="$t('searchTable.actions.refresh')">
            <div class="action-icon" @click="search"
              ><icon-refresh size="18"
            /></div>
          </a-tooltip>
          <a-dropdown @select="handleSelectDensity">
            <a-tooltip content="密度">
              <div class="action-icon"><icon-line-height size="18" /></div>
            </a-tooltip>
            <template #content>
              <a-doption
                v-for="item in densityList"
                :key="item.value"
                :value="item.value"
                :class="{ active: item.value === size }"
              >
                <span>{{ item.name }}</span>
              </a-doption>
            </template>
          </a-dropdown>
          <a-tooltip :content="$t('searchTable.actions.columnSetting')">
            <a-popover
              trigger="click"
              position="bl"
              @popup-visible-change="popupVisibleChange"
            >
              <div class="action-icon"><icon-settings size="18" /></div>
              <template #content>
                <div id="tableSetting">
                  <div
                    v-for="(item, index) in showColumns"
                    :key="item.dataIndex"
                    class="setting"
                  >
                    <div style="margin-right: 4px; cursor: move">
                      <icon-drag-arrow />
                    </div>
                    <div>
                      <a-checkbox
                        v-model="item.checked"
                        @change="
                          handleChange($event, item as TableColumnData, index)
                        "
                      >
                      </a-checkbox>
                    </div>
                    <div class="title">
                      {{ item.title === '#' ? '序列号' : item.title }}
                    </div>
                  </div>
                </div>
              </template>
            </a-popover>
          </a-tooltip>
        </a-col>
      </a-row>

      <a-table
        <#list table.fields as field>
        <#if field.keyFlag>
        row-key="${field.propertyName}"
        </#if>
        </#list>
        :loading="loading"
        :pagination="pagination"
        :columns="(cloneColumns as TableColumnData[])"
        :data="renderData"
        :bordered="false"
        :size="size"
        @page-change="onPageChange"
      >
        <template #operations="{ record }">
          <a-button
                  type="dashed"
                  size="small"
                  status="warning"
                  @click="edit(record.id)"
          >
            编辑
          </a-button>
          <a-divider direction="vertical"/>
          <a-popconfirm
                  content="确定删除?"
                  type="warning"
                  @ok="deleteRow(record.id)"
          >
            <a-button
                    type="dashed"
                    size="small"
                    status="warning"
            >
              删除
            </a-button>
          </a-popconfirm>
        </template>

      </a-table>
      <Form ref="formRef" @ok="fetchData" />
    </a-card>
  </div>
</template>

<script lang="ts" setup>
import {computed, nextTick, reactive, ref, watch} from 'vue';
import {useI18n} from 'vue-i18n';
import useLoading from '@/hooks/loading';
import {queryPage,removeRow,addForm,editForm} from '@/api/${busName}';
import {Pagination} from '@/types/global';
import type {SelectOptionData} from '@arco-design/web-vue/es/select/interface';
import type {TableColumnData} from '@arco-design/web-vue/es/table/interface';
import cloneDeep from 'lodash/cloneDeep';
import Sortable from 'sortablejs';
import {PageParams, PageRes} from '@/api/common';
import {Message} from "@arco-design/web-vue";
import Form from './form.vue';

type SizeProps = 'mini' | 'small' | 'medium' | 'large';
type Column = TableColumnData & { checked?: true };

  const searchForm = () => {
    return {
      <#list columnRows as columnRow>
      <#if columnRow.queryWhether?? && columnRow.queryWhether=="Y">
        <#if columnRow.fieldJavaType?? && columnRow.fieldJavaType=="String">
          ${columnRow.fieldName}:'',
          <#elseif columnRow.fieldJavaType?? && columnRow.fieldJavaType=="Integer" ||  columnRow.fieldJavaType=="Long" ||  columnRow.fieldJavaType=="Double">
          ${columnRow.fieldName}:0,
           <#else>
          ${columnRow.fieldName}:null,
        </#if>
      </#if>
      </#list>
    };
  };
  const { loading, setLoading } = useLoading(true);
  const { t } = useI18n();
  const renderData = ref<PageRes[]>([]);
  const formModel = ref(searchForm());
  const cloneColumns = ref<Column[]>([]);
  const showColumns = ref<Column[]>([]);
  const formRef = ref<any>();

  const size = ref<SizeProps>('medium');

  const basePagination: Pagination = {
    current: 1,
    pageSize: 10,
    desc:[],
    asc:[]
  };
  const pagination = reactive({
    ...basePagination,
  });
  const densityList = computed(() => [
    {
      name: t('searchTable.size.mini'),
      value: 'mini',
    },
    {
      name: t('searchTable.size.small'),
      value: 'small',
    },
    {
      name: t('searchTable.size.medium'),
      value: 'medium',
    },
    {
      name: t('searchTable.size.large'),
      value: 'large',
    },
  ]);
  const columns = computed<TableColumnData[]>(() => [

  <#list columnRows as columnRow>
    <#if columnRow.whetherTable?? && columnRow.whetherTable=="Y">
    {
      title: '${columnRow.fieldRemark}',
      dataIndex: '${columnRow.fieldName}'
    },
    </#if>
  </#list>
    {
      title: t('searchTable.columns.operations'),
      dataIndex: 'operations',
      slotName: 'operations',
    }
  ]);
  const xxxOption = computed<SelectOptionData[]>(() => [
    {
      label: '全部',
      value: '',
    },
    {
      label: '男',
      value: '1',
    },
    {
      label: '女',
      value: '2',
    }
  ]);

  const statusOptions = computed<SelectOptionData[]>(() => [
    {
      label: t('searchTable.form.status.online'),
      value: 'online',
    },
    {
      label: t('searchTable.form.status.offline'),
      value: 'offline',
    },
  ]);
  const fetchData = async (
    params: PageParams = { current: 1, pageSize: 10,desc:[],asc:[] }
  ) => {
    setLoading(true);
    try {
      const { data } = await queryPage(params);
      renderData.value = data.records;
      pagination.current = params.current;
      pagination.total = data.total;
    } catch (err) {
      console.log(err);
    } finally {
      setLoading(false);
    }
  };

  const search = () => {
    fetchData({
      ...basePagination,
      ...formModel.value,
    } as unknown as PageParams);
  };
  const onPageChange = (current: number) => {
    fetchData({ ...basePagination, current });
  };

  const deleteRow = async (id: string) => {
    await removeRow(id);
    await fetchData();
    Message.success('操作成功!');
  };

  fetchData();
  const reset = () => {
    formModel.value = searchForm();
    search();
  };

  const handleSelectDensity = (
    val: string | number | Record<string, any> | undefined,
    e: Event
  ) => {
    size.value = val as SizeProps;
  };

  const handleChange = (
    checked: boolean | (string | boolean | number)[],
    column: Column,
    index: number
  ) => {
    if (!checked) {
      cloneColumns.value = showColumns.value.filter(
        (item) => item.dataIndex !== column.dataIndex
      );
    } else {
      cloneColumns.value.splice(index, 0, column);
    }
  };

  const remove = async (id: string) => {
    const res = await removeRow(id);
    search();
  }

  const add = async () => {
    formRef.value.addForm();
  };

  const edit = async (id: string) => {
    formRef.value.editForm(id);
  };

  const exchangeArray = <T extends Array<any>>(
    array: T,
    beforeIdx: number,
    newIdx: number,
    isDeep = false
  ): T => {
    const newArray = isDeep ? cloneDeep(array) : array;
    if (beforeIdx > -1 && newIdx > -1) {
      // 先替换后面的，然后拿到替换的结果替换前面的
      newArray.splice(
        beforeIdx,
        1,
        newArray.splice(newIdx, 1, newArray[beforeIdx]).pop()
      );
    }
    return newArray;
  };

  const popupVisibleChange = (val: boolean) => {
    if (val) {
      nextTick(() => {
        const el = document.getElementById('tableSetting') as HTMLElement;
        const sortable = new Sortable(el, {
          onEnd(e: any) {
            const { oldIndex, newIndex } = e;
            exchangeArray(cloneColumns.value, oldIndex, newIndex);
            exchangeArray(showColumns.value, oldIndex, newIndex);
          },
        });
      });
    }
  };

  watch(
    () => columns.value,
    (val) => {
      cloneColumns.value = cloneDeep(val);
      cloneColumns.value.forEach((item, index) => {
        item.checked = true;
      });
      showColumns.value = cloneDeep(cloneColumns.value);
    },
    { deep: true, immediate: true }
  );
</script>

<script lang="ts">
  export default {
    name: 'SearchTable',
  };
</script>

<style scoped lang="less">
  .container {
    padding: 0 20px 20px 20px;
  }
  :deep(.arco-table-th) {
    &:last-child {
      .arco-table-th-item-title {
        margin-left: 16px;
      }
    }
  }
  .action-icon {
    margin-left: 12px;
    cursor: pointer;
  }
  .active {
    color: #0960bd;
    background-color: #e3f4fc;
  }
  .setting {
    display: flex;
    align-items: center;
    width: 200px;
    .title {
      margin-left: 12px;
      cursor: pointer;
    }
  }
</style>
